from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Optional
from datetime import datetime
from decimal import Decimal

from .schemas import (
    SignalCollectionIn, SignalCollectionOut, 
    DeviceInfoIn, DeviceInfoOut, SignalStatisticsOut
)
from .simple_storage import storage

app = FastAPI(title="GSignal Backend - Simple Version", version="0.1.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow(),
        "database": "memory_storage"
    }

@app.post("/signal/collect", response_model=SignalCollectionOut)
async def collect_signal(signal_data: SignalCollectionIn):
    """采集4G信号数据"""
    try:
        # 转换Pydantic模型为字典
        data_dict = signal_data.dict()
        
        # 处理Decimal类型
        for key, value in data_dict.items():
            if isinstance(value, Decimal):
                data_dict[key] = float(value)
        
        # 处理datetime类型
        if "collected_at" in data_dict:
            data_dict["collected_at"] = data_dict["collected_at"].isoformat()
        
        result = await storage.create_signal_collection(data_dict)
        
        # 转换回Pydantic模型
        return SignalCollectionOut(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"信号采集失败: {str(e)}")

@app.get("/signal/collections", response_model=List[SignalCollectionOut])
async def get_signal_collections(
    device_id: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    offset: int = 0
):
    """获取信号采集记录列表"""
    try:
        results = await storage.get_signal_collections(
            device_id=device_id,
            start_time=start_time,
            end_time=end_time,
            limit=limit,
            offset=offset
        )
        
        return [SignalCollectionOut(**result) for result in results]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取信号记录失败: {str(e)}")

@app.get("/signal/statistics/{device_id}", response_model=SignalStatisticsOut)
async def get_signal_statistics(device_id: str):
    """获取设备信号统计信息"""
    try:
        statistics = await storage.get_signal_statistics(device_id)
        if not statistics:
            raise HTTPException(status_code=404, detail="未找到该设备的统计信息")
        
        return SignalStatisticsOut(**statistics)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")

@app.post("/device/register", response_model=DeviceInfoOut)
async def register_device(device_info: DeviceInfoIn):
    """注册设备信息"""
    try:
        data_dict = device_info.dict()
        result = await storage.register_device(data_dict)
        return DeviceInfoOut(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设备注册失败: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8886)